package com.ygxsk.carhome.ui.consign;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.ConsignMainTitle;
import com.ygxsk.carhome.enumwrap.ConsignStatus;
import com.ygxsk.carhome.event.EventConsignMain;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.ButtonAutoCancelListener;
import com.ygxsk.carhome.response.ConsignmentOutSide;
import com.ygxsk.carhome.response.ConsignmentVo;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.BaseImmersionFragment;
import com.ygxsk.carhome.ui.adapter.ConsignMainAdapter;
import com.ygxsk.carhome.ui.auth.AuthCancelEditReasonPopu;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ConsignMainFragment#newInstance} factory method to
 * create an instance of this fragment.在线寄售的碎片；
 */
public class ConsignMainFragment extends BaseImmersionFragment implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.refreshlayoutconsignfragment)
    SmartRefreshLayout refreshLayoutConsignFragment;

    @BindView(R.id.recyclerviewinconsignfragment)
    RecyclerView recyclerViewInConsignFragment;

    private ArrayList<ConsignmentVo> mDataResources = new ArrayList<>();

    private ConsignMainAdapter consignMainAdapter;

    private int pagination_upLoad = Parameterkey.pageNum_default_first;

    private BGANinePhotoLayout mCurrentClickNpl;
    //取消原因的 弹窗布局
    private BasePopupView basePopupView_cancelReason;
    //确认的弹窗，因为底部有一个弹窗，不用这个弹窗会造成确认按钮无法点击
    private BasePopupView popupViewConfirm;
    //该页面仅仅只有预览的能力
    private static final int PRC_PHOTO_PREVIEW = 1;

    //给列表九宫格查看准备
    private BGANinePhotoLayout.Delegate bgaNinePhotoLayoutDelegate = new BGANinePhotoLayout.Delegate() {
        @Override
        public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
            //点击九宫格,查看大图
            mCurrentClickNpl = ninePhotoLayout;

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                photoPreviewWrapper();

            } else {

                photoPreviewIntentXXPermissions();

            }

        }

        @Override
        public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
            //点击展开的
            ninePhotoLayout.setIsExpand(true);
            ninePhotoLayout.flushItems();
        }
    };

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

        if (EasyPermissions.hasPermissions(this.getContext(), perms)) {

            CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

        } else {
            //EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", PRC_PHOTO_PREVIEW, perms);
            EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imagenicelook), PRC_PHOTO_PREVIEW, perms);
        }
    }

    private void photoPreviewIntentXXPermissions() {

        if (!XXPermissions.isGranted(ConsignMainFragment.this.getContext(), com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(ConsignMainFragment.this.getContext())
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
//                    .permission(com.hjq.permissions.Permission.CAMERA)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
                            .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(ConsignMainFragment.this.getContext(), permissions)));

                                    CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

                                }
                            });

                }
            });


        } else {

            CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

        }

    }

//    private void photoPreviewIntent() {
//
//        //            File downloadDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//
//        File downloadDir = new File(PathUtils.getExternalAppFilesPath(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//
//        BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(this.getContext());
//
//        if (true) {
//            // 保存图片的目录，如果传 null，则没有保存图片功能
//            photoPreviewIntentBuilder.saveImgDir(downloadDir);
//
//        }
//
//        if (mCurrentClickNpl.getItemCount() == 1) {
//            // 预览单张图片
//            photoPreviewIntentBuilder.previewPhoto(mCurrentClickNpl.getCurrentClickItem());
//
//        } else if (mCurrentClickNpl.getItemCount() > 1) {
//            // 预览多张图片
//            photoPreviewIntentBuilder.previewPhotos(mCurrentClickNpl.getData())
//                    .currentPosition(mCurrentClickNpl.getCurrentClickItemPosition()); // 当前预览图片的索引
//        }
//
//        startActivity(photoPreviewIntentBuilder.build());
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PREVIEW) {
            //Toast.makeText(this, StringUtils.getString(R.string.image_preview), Toast.LENGTH_SHORT).show();
            ToastUtils.showShort(StringUtils.getString(R.string.image_preview));
        }
    }

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM_INDEX = "arg_param_index";
    private static final String ARG_PARAM_TITLE_NAME = "arg_param_title_name";

    //携带过来的两个参数
    private String arg_param_index = "";
    private String arg_param_title_name = "";

    public ConsignMainFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ConsignMainFragment.
     */
    public static ConsignMainFragment newInstance(String index, String titleName) {

        ConsignMainFragment fragment = new ConsignMainFragment();

        Bundle args = new Bundle();
        args.putString(ARG_PARAM_INDEX, index);
        args.putString(ARG_PARAM_TITLE_NAME, titleName);

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mFragmentInstance = this;
        mActivityInstance = this.getActivity();

        if (getArguments() != null) {
            arg_param_index = getArguments().getString(ARG_PARAM_INDEX);
            arg_param_title_name = getArguments().getString(ARG_PARAM_TITLE_NAME);
        }

        //initLoading(mRootView);

        //列表之内需要向外部广播数据
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initView() {

        //initLoading(mRootView);
        super.initView();

        recyclerViewInConsignFragment.setLayoutManager(new MyLinearLayoutManager(this.getContext()));

        consignMainAdapter = new ConsignMainAdapter(R.layout.consignmainadapter, mDataResources);
        if (bgaNinePhotoLayoutDelegate != null) {
            consignMainAdapter.setBgaNinePhotoLayoutDelegate(bgaNinePhotoLayoutDelegate);
        }

        recyclerViewInConsignFragment.setAdapter(consignMainAdapter);
        consignMainAdapter.notifyDataSetChanged();
        consignMainAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                ConsignmentVo consignmentVo = (ConsignmentVo) adapter.getItem(position);

                if (consignmentVo != null) {

                    switch (view.getId()) {

                        case R.id.roundtextviewverifyconsign: {//审核通过

                            CommUtils.checkDialog(mAlertView);
                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                    StringUtils.getString(R.string.submit_consign_verify_message),//提示内容 确定审核通过
                                    StringUtils.getString(R.string.clearcachecancel), //取消
                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                                @Override
                                public void onItemClick(Object o, int position) {

                                    if (position != AlertView.CANCELPOSITION) {

                                        method_gainVerifySubmitInfo_upLoad(consignmentVo.getConsignmentId());

                                    }

                                }
                            });

                            mAlertView.setCancelable(true);
                            mAlertView.show();

                            break;
                        }

                        case R.id.roundtextviewhascontacted: {//已联系

                            CommUtils.checkDialog(mAlertView);
                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                    StringUtils.getString(R.string.submit_sure_message),//提示内容：确定和客户取得联系
                                    StringUtils.getString(R.string.clearcachecancel), //取消
                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                                @Override
                                public void onItemClick(Object o, int position) {

                                    if (position != AlertView.CANCELPOSITION) {

                                        method_gainHasContactedSubmitInfo_upLoad(consignmentVo.getConsignmentId());

                                    }

                                }
                            });

                            mAlertView.setCancelable(true);
                            mAlertView.show();

                            break;
                        }

                        case R.id.roundtextviewcancelconsign: {//取消审核

                            //弹窗填写取消原因
                            basePopupView_cancelReason = new XPopup.Builder(mFragmentInstance.getContext())
                                    .hasShadowBg(true)
                                    //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面;
                                    .isViewMode(true)
                                    .autoFocusEditText(true)//
                                    .autoOpenSoftInput(true)//
                                    .asCustom(new AuthCancelEditReasonPopu(mFragmentInstance.getContext(),//
                                            ExtraValue.VALUE_JUMP_FORM_CONSIGN_MAINLIST_CANCEL_REASON, new ButtonAutoCancelListener() {

                                        @Override
                                        public void buttonAuthCancel() {

                                            if (basePopupView_cancelReason != null) {
                                                basePopupView_cancelReason.dismiss();
                                            }

                                        }

                                        @Override
                                        public void buttonAuthSure(String cancelReason) {

                                            KeyboardUtils.hideSoftInput(ConsignMainFragment.this.getActivity());

                                            //校验取消的原因：
                                            if (TextUtils.isEmpty(cancelReason)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                                                //因为确认弹窗会被填写原因的弹窗遮盖
//                                        CommUtils.checkDialog(mAlertView);
//                                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_auth_cancel_reason_upload), true);
//                                        mAlertView.show();
                                                PopTip.show(StringUtils.getString(R.string.check_auth_cancel_reason_upload)).iconError();

                                                return;
                                            }

                                            popupViewConfirm = new XPopup.Builder(mFragmentInstance.getContext())
                                                    .isDestroyOnDismiss(true)
                                                    .asConfirm(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //标题
                                                            StringUtils.getString(R.string.submit_repair_cancel_message),//文本内容:确定取消吗？
                                                            StringUtils.getString(R.string.clearcachecancel), //取消按钮
                                                            StringUtils.getString(R.string.clearcachetitlesure),//确定按钮
                                                            new OnConfirmListener() {
                                                                @Override
                                                                public void onConfirm() {

                                                                    method_gainCancelSubmitInfo_upLoad(consignmentVo.getConsignmentId(), cancelReason);

                                                                }
                                                            }, null, false);

                                            popupViewConfirm.show();

                                        }
                                    }))//
                                    .show();


                            break;
                        }

                        case R.id.textviewphoneconsignmain: {//拨打电话 的按钮

                            clickButton_toCallPhone(mActivityInstance, consignmentVo.getCustomerPhone(), CallHistoryBusinessType.BUSINESSTYPE_6.getIndex());

                            break;
                        }

                        default:
                            break;
                    }


                }

            }
        });

        refreshLayoutConsignFragment.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        pagination_upLoad = Parameterkey.pageNum_default_first;

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        getServerDatas();

                        refreshLayout.finishRefresh();
                    }
                });
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        getServerDatas();

                        refreshLayout.finishLoadMore();

                    }
                });
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();

        gainDatas();

    }

    private void getServerDatas() {

//        ConsignStatus
//                STATUS_NOT_CONTACT("0", "待联系"),
//                STATUS_HAS_CONTACT("1", "已联系"),
//                STATUS_HAS_VERIFY("2", "已审核"),
//                STATUS_HAS_PUBLISH("3", "已发布"),
//                STATUS_HAS_CANCEL("4", "已取消");

        //获取：寄售状态：0:待联系;1:已联系;2:已审核;3已发布;4已取消
        // 寄售状态：0:待联系;1:已联系;2:已审核;3已发布;4已取消
//        ArrayList<String> tempList = new ArrayList<>();
//        tempList.add(ConsignStatus.STATUS_NOT_CONTACT.getIndex().trim());//0:待联系
//        tempList.add(ConsignStatus.STATUS_HAS_CONTACT.getIndex().trim());//1:已联系
//        tempList.add(ConsignStatus.STATUS_HAS_VERIFY.getIndex().trim());//2:已审核

        HashMap<String, Object> hashMapParameter = new HashMap<>();
        hashMapParameter.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        hashMapParameter.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        hashMapParameter.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        //获取：寄售状态：0:待联系;1:已联系;2:已审核;3已发布;4已取消
        StringBuffer stringBuffer = new StringBuffer();

        if (TextUtils.equals(arg_param_index, ConsignMainTitle.TITLE_ALL.getIndex())) {
            //全部
            stringBuffer.append(ConsignStatus.STATUS_NOT_CONTACT.getIndex().trim())//
                    .append(",")//
                    .append(ConsignStatus.STATUS_HAS_CONTACT.getIndex().trim())//
                    .append(",")//
                    .append(ConsignStatus.STATUS_HAS_VERIFY.getIndex().trim());//

        } else if (TextUtils.equals(arg_param_index, ConsignMainTitle.TITLE_NOT_CONTACT.getIndex())) {
            //待联系
            stringBuffer.append(ConsignStatus.STATUS_NOT_CONTACT.getIndex().trim());

        } else if (TextUtils.equals(arg_param_index, ConsignMainTitle.TITLE_HAS_CONTACT.getIndex())) {
            //已联系
            stringBuffer.append(ConsignStatus.STATUS_HAS_CONTACT.getIndex().trim());

        } else if (TextUtils.equals(arg_param_index, ConsignMainTitle.TITLE_HAS_VERIFY.getIndex())) {
            //已审核
            stringBuffer.append(ConsignStatus.STATUS_HAS_VERIFY.getIndex().trim());

        } else {

            //默认的传递全部，不能让列表没有数据
            stringBuffer.append(ConsignStatus.STATUS_NOT_CONTACT.getIndex().trim())//
                    .append(",")//
                    .append(ConsignStatus.STATUS_HAS_CONTACT.getIndex().trim())//
                    .append(",")//
                    .append(ConsignStatus.STATUS_HAS_VERIFY.getIndex().trim());//

        }

        hashMapParameter.put(Parameterkey.statusStr, stringBuffer.toString());

//        map.put(Parameterkey.keyWord, keyWord_upLoad);//,搜索关键字
//        map.put(Parameterkey.latentType, latentType_upLoad);//,潜客类型 1新车;2二手车
//        map.put(Parameterkey.createsource, createsource_upLoad);//客户来源：0预约试驾；1预约看车；2自然到店；3以旧换新

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETMYCONSIGNMENTLISTBYPAGE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getMyConsignmentListByPage_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(hashMapParameter);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getMyConsignmentListByPage(RequestBody.create(JSON.toJSONString(hashMapParameter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                //.compose(mActivityInstance.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ConsignmentOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL+"handlerSomeThingNotSuccessDataForItSelf");

                        methodNotSuccessData(what_method, serverCode, serverMessage);

//                        if (!TextUtils.isEmpty(serverMessage)) {
//                            ToastUtils.showShort(serverMessage);
//                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();

                        if (refreshLayoutConsignFragment != null) {
                            refreshLayoutConsignFragment.setEnableLoadMore(true);
                        }
                    }
                }).subscribe(new Consumer<ConsignmentOutSide>() {
                    @Override
                    public void accept(ConsignmentOutSide consignmentOutSide) throws Throwable {

                        if (consignmentOutSide != null) {

                            ArrayList<ConsignmentVo> currentDatas = consignmentOutSide.getDataList();

                            if (currentDatas != null && !currentDatas.isEmpty()) {
                                if (mDataResources != null) {
                                    mDataResources.addAll(currentDatas);
                                }
                            }
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            //同时禁用加载更多；
                            if (refreshLayoutConsignFragment != null) {
                                refreshLayoutConsignFragment.setEnableLoadMore(false);
                            }
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }


                        if (consignMainAdapter != null) {
                            consignMainAdapter.notifyDataSetChanged();
                        }

                        //给分页值
                        pagination_upLoad = consignmentOutSide.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutConsignFragment, true);
                        } else {
                            setEnableLoadmore(refreshLayoutConsignFragment, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.WHAT_GETMYCONSIGNMENTLISTBYPAGE_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

                    if (refreshLayoutConsignFragment != null) {
                        refreshLayoutConsignFragment.setEnableLoadMore(false);
                    }

                    CommUtils.checkCurrently(mFragmentInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }


    //【取消在线寄售】接口
    private void method_gainCancelSubmitInfo_upLoad(String _getConsignmentId, String _cancelReason) {

//        在线寄售的状态：寄售状态：0:待联系;1:已联系;2:已审核;3已发布;4已取消
//        ConsignStatus
//                STATUS_NOT_CONTACT("0", "待联系"),
//                STATUS_HAS_CONTACT("1", "已联系"),
//                STATUS_HAS_VERIFY("2", "已审核"),
//                STATUS_HAS_PUBLISH("3", "已发布"),
//                STATUS_HAS_CANCEL("4", "已取消");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.consignmentId, _getConsignmentId);//
        map.put(Parameterkey.status, ConsignStatus.STATUS_HAS_CANCEL.getIndex());//4:已取消 即意义为：将状态更改为 已取消；
        // : 2023-08-13 09:08 取消在线寄售的原因，这里待确认！
        map.put(Parameterkey.remark, _cancelReason);//取消在线寄售的原因,是必填

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECONSIGNMENT_CANCEL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateConsignment_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateConsignment(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                //.compose(ConsignMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        KeyboardUtils.hideSoftInput(ConsignMainFragment.this.getActivity());

                        if (basePopupView_cancelReason != null) {
                            basePopupView_cancelReason.dismiss();
                            basePopupView_cancelReason.onDestroy();
                        }

                        //通知主页列表刷新
                        EventConsignMain eventConsignMain = new EventConsignMain();
                        eventConsignMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CONSIGN_MAIN_LIST);
                        EventBus.getDefault().post(eventConsignMain);

                        methodSubmitSuccess(mActivityInstance, null);


//                        methodSubmitSuccess(ConsignMainActivity.this, new DoSomeThingListener() {
//                            @Override
//                            public void doSomeThing() {
//                                //应该是仅仅刷新列表即可
//                            }
//                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }

    //【已联系】接口
    private void method_gainHasContactedSubmitInfo_upLoad(String _getConsignmentId) {

//        在线寄售的状态：寄售状态：0:待联系;1:已联系;2:已审核;3已发布;4已取消
//                ConsignStatus
//                STATUS_NOT_CONTACT("0", "待联系"),
//                STATUS_HAS_CONTACT("1", "已联系"),
//                STATUS_HAS_VERIFY("2", "已审核"),
//                STATUS_HAS_PUBLISH("3", "已发布"),
//                STATUS_HAS_CANCEL("4", "已取消");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.consignmentId, _getConsignmentId);//
        map.put(Parameterkey.status, ConsignStatus.STATUS_HAS_CONTACT.getIndex());//1:已联系 即 已经

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECONSIGNMENT_VERIFY);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateConsignment_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateConsignment(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                //.compose(ConsignMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //通知主页列表刷新
                        EventConsignMain eventConsignMain = new EventConsignMain();
                        eventConsignMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CONSIGN_MAIN_LIST);
                        EventBus.getDefault().post(eventConsignMain);

                        methodSubmitSuccess(mActivityInstance, null);

//                        methodSubmitSuccess(ConsignMainActivity.this, new DoSomeThingListener() {
//                            @Override
//                            public void doSomeThing() {
//                                //应该是仅仅刷新列表即可
//                            }
//                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }


    //【审核通过】接口
    private void method_gainVerifySubmitInfo_upLoad(String _getConsignmentId) {

//        在线寄售的状态：寄售状态：0:待联系;1:已联系;2:已审核;3已发布;4已取消
//        ConsignStatus
//                STATUS_NOT_CONTACT("0", "待联系"),
//                STATUS_HAS_CONTACT("1", "已联系"),
//                STATUS_HAS_VERIFY("2", "已审核"),
//                STATUS_HAS_PUBLISH("3", "已发布"),
//                STATUS_HAS_CANCEL("4", "已取消");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.consignmentId, _getConsignmentId);//
        map.put(Parameterkey.status, ConsignStatus.STATUS_HAS_VERIFY.getIndex());//2:已审核 即审核通过状态

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECONSIGNMENT_VERIFY);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateConsignment_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateConsignment(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                //.compose(ConsignMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //通知主页列表刷新
                        EventConsignMain eventConsignMain = new EventConsignMain();
                        eventConsignMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CONSIGN_MAIN_LIST);
                        EventBus.getDefault().post(eventConsignMain);

                        methodSubmitSuccess(mActivityInstance, null);

//                        methodSubmitSuccess(ConsignMainActivity.this, new DoSomeThingListener() {
//                            @Override
//                            public void doSomeThing() {
//                                //应该是仅仅刷新列表即可
//                            }
//                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (consignMainAdapter != null) {
            consignMainAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {

            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutConsignFragment, false);

        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_consign_main;
    }

    @Override
    public void onClickNodata(View view) {

        gainDatas();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInConsignMainFragment(EventConsignMain eventConsignMain) {

        if (eventConsignMain != null) {

            if (eventConsignMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CONSIGN_MAIN_LIST) {

                pagination_upLoad = Parameterkey.pageNum_default_first;

                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

//                if (consignMainAdapter != null) {
//                    consignMainAdapter.notifyDataSetChanged();
//                }

                getServerDatas();

            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (consignMainAdapter != null) {
            consignMainAdapter.notifyDataSetChanged();
            consignMainAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

        if (mCurrentClickNpl != null) {
            mCurrentClickNpl = null;
        }

        CommUtils.checkBasePopupView(basePopupView_cancelReason);
        CommUtils.checkBasePopupView(popupViewConfirm);

        EventBus.getDefault().unregister(this);
    }
}